import java.util.HashSet;
import java.util.Set;

/*
 * @lc app=leetcode.cn id=142 lang=java
 *
 * [142] 环形链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {

    /**
     * Accepted
    17/17 cases passed (0 ms)
    Your runtime beats 100 % of java submissions
    Your memory usage beats 69.15 % of java submissions (41.6 MB)
     */
    public ListNode detectCycle(ListNode head) {
        ListNode s = head, f = head;
        while (true) {
            if (f == null || f.next == null)
                return null;
            s = s.next;
            f = f.next.next;
            if (s == f)
                break;
        }
        f = head;
        while (s != f) {
            s = s.next;
            f = f.next;
        }
        return f;
    }
}
// @lc code=end
